package com.yungu.swift.common.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.yungu.swift.base.model.config.SmsConfig;
import com.yungu.swift.base.model.config.SysConfig;
import com.yungu.swift.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author : cuixiuyin
 * @date : 2019/7/30
 */
@Slf4j
@Configuration
public class NacosListener {

    @Value("${nacos.host:127.0.0.1:8848}")
    private String host;
    @Value("${nacos.namespace:}")
    private String namespace;
    private String GROUP = "DEFAULT_GROUP";

    public static SmsConfig SMS_CONFIG;

    public static SysConfig SYS_CONFIG;

    @PostConstruct
    public void init() {
        Properties properties = new Properties();
        properties.put("serverAddr", host);
        properties.put("namespace", namespace);
        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            // 短信配置项监听
            configService.addListener("SMS_CONFIG", GROUP, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("receive sysconfig value:{}", configInfo);
                    try {
                        SMS_CONFIG = Optional.ofNullable(JsonUtils.readValue(configInfo, SmsConfig.class)).orElse(new SmsConfig());
                    } catch (IOException e) {
                        log.error("NacosListener init Listener JsonUtils readValue SmsConfig error.", e);
                    }
                }
            });
            // 系统配置项监听
            configService.addListener("SYS_CONFIG", GROUP, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("receive sysconfig value:{}", configInfo);
                    try {
                        SYS_CONFIG = Optional.ofNullable(JsonUtils.readValue(configInfo, SysConfig.class)).orElse(new SysConfig());
                    } catch (IOException e) {
                        log.error("NacosListener init Listener JsonUtils readValue SysConfig error.", e);
                    }
                }
            });
        } catch (NacosException e) {
            log.error("NacosListener init createConfigService error.", e);
        }
    }
}
